package com.jhgsys.internal.hazard.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jhgsys.internal.base.entity.BaseCautionaryLesson;
import com.jhgsys.internal.base.service.IBaseCautionaryLessonService;
import com.jhgsys.internal.common.annotation.Log;
import com.jhgsys.internal.common.constant.ModuleManagerPermissionConstant;
import com.jhgsys.internal.common.controller.BaseController;
import com.jhgsys.internal.common.entity.FebsConstant;
import com.jhgsys.internal.common.entity.FebsResponse;
import com.jhgsys.internal.common.entity.QueryRequest;
import com.jhgsys.internal.common.entity.FebsConstant;
import com.jhgsys.internal.common.exception.FebsException;
import com.jhgsys.internal.common.utils.FebsUtil;
import com.jhgsys.internal.hazard.constant.HazardConstant;
import com.jhgsys.internal.hazard.dto.HazardReportDto;
import com.jhgsys.internal.hazard.entity.HazardReport;
import com.jhgsys.internal.hazard.entity.HazardReportConfig;
import com.jhgsys.internal.hazard.service.IHazardReportConfigService;
import com.jhgsys.internal.hazard.service.IHazardReportService;
import com.wuwenze.poi.ExcelKit;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import javax.validation.constraints.NotBlank;
import java.util.Date;
import java.util.stream.Collectors;

/**
 * 隐患上报 Controller
 *
 * @author wanghw
 * @date 2024-08-20 09:23:04
 */
@Slf4j
@Validated
@Controller
public class HazardReportController extends BaseController {

    @Autowired
    private IHazardReportService hazardReportService;

    @Autowired
    private IBaseCautionaryLessonService baseCautionaryLessonService;

    @Autowired
    private IHazardReportConfigService hazardReportConfigService;

    @GetMapping(FebsConstant.VIEW_PREFIX + "hazardReport")
    @RequiresPermissions("hazardReport:view")
    public String hazardReportIndex(Model model){
        model.addAttribute("hasHeadCompanyRole", hasHeadCompanyRole());
        model.addAttribute("tenantList",getTenantList());
        model.addAttribute("currentTenantId", getCurrentTenantId());
        return FebsUtil.view("hazard/hazardReport/hazardReportList");
    }



    @GetMapping(FebsConstant.VIEW_PREFIX + "hazardReport/add/{tenantId}")
    @RequiresPermissions("hazardReport:add")
    public String hazardReportAdd(Model model, @PathVariable("tenantId") String tenantId){
        model.addAttribute("hasHeadCompanyRole", hasHeadCompanyRole());
        model.addAttribute("tenantList",getTenantList());
        model.addAttribute("currentTenantId", tenantId);
        return FebsUtil.view("hazard/hazardReport/hazardReportEdit");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "hazardReport/update/{id}")
    @RequiresPermissions("hazardReport:edit")
    public String hazardReportUpdate(Model model, @PathVariable("id") String id) throws JsonProcessingException {
        HazardReportDto dto = hazardReportService.findHazardReportById(id);
        model.addAttribute("hasHeadCompanyRole", hasHeadCompanyRole());
        model.addAttribute("tenantList",getTenantList());
        model.addAttribute("currentTenantId", dto.getTenantId());
        model.addAttribute("hazardReport", JSON.parse(new ObjectMapper().writeValueAsString(dto)));
        return FebsUtil.view("hazard/hazardReport/hazardReportEdit");
    }

    /**
     * 查询（所有）
     * @author wanghw
     * @date 2024-08-20 09:23:04
     */
    @GetMapping("hazardReport")
    @ResponseBody
    @RequiresPermissions("hazardReport:view")
    public FebsResponse getAllHazardReports(HazardReport hazardReport) {
        return new FebsResponse().success().data(hazardReportService.findHazardReportList(hazardReport));
    }

    /**
     * 查询（分页）
     * @author wanghw
     * @date 2024-08-20 09:23:04
     */
    @GetMapping("hazardReport/list")
    @ResponseBody
    @RequiresPermissions("hazardReport:view")
    public FebsResponse hazardReportList(QueryRequest request, HazardReportDto hazardReport) {
        List<String> statusList = Arrays.asList(HazardConstant.HAZARD_STATUS.UPLOAD,HazardConstant.HAZARD_STATUS.BACK_PLAN);
        hazardReport.setStatus(statusList.stream().collect(Collectors.joining(StringPool.COMMA)));
        //不是总公司，或者不是模块管理员，则只查自己的
        if(!hasHeadCompanyRole() && !hasPermission(ModuleManagerPermissionConstant.HAZARD)){
            hazardReport.setCreatedBy(getCurrentUser().getUserName());
        }
        Map<String, Object> dataTable = getDataTable(this.hazardReportService.findHazardReportPage(request, hazardReport));
        return new FebsResponse().success().data(dataTable);
    }

    /**
     * 新增 隐患上报
     * @author wanghw
     * @date 2024-08-20 09:23:04
     */
    @Log("新增隐患上报")
    @PostMapping("hazardReport")
    @ResponseBody
    @RequiresPermissions("hazardReport:add")
    public FebsResponse addHazardReport(@RequestBody HazardReportDto hazardReport) throws FebsException {

        try {
            checkParams(hazardReport);
            if(!HazardConstant.HAZARD_STATUS.UPLOAD.equals(hazardReport.getStatus()) &&
                    !HazardConstant.HAZARD_STATUS.PLAN.equals(hazardReport.getStatus())){
                throw new FebsException("非法的隐患状态");
            }
            if(HazardConstant.HAZARD_STATUS.PLAN.equals(hazardReport.getStatus())){
                HazardReportConfig config = hazardReportConfigService.findHazardReportConfigByTenantId(getCurrentTenantId());
                if(ObjectUtils.isNotEmpty(config) && config.getReportNumber() !=0){
                    int submitNums = hazardReportService.countTodayByUserName(getCurrentUser().getUserName());
                    if(submitNums >= config.getReportNumber()){
                        return new FebsResponse().fail().message("当天提交报告数已达最大次数");
                    }
                }
            }
            hazardReport.setCreatedBy(getCurrentUser().getUserName());
//            hazardReport.setStatus(HazardConstant.HAZARD_STATUS.UPLOAD);
            hazardReport.setForwardFlg(HazardConstant.FORWARD_FLG.UN_FORWARD);
            hazardReport.setReportNo(hazardReportService.createHazardReportNo(hazardReport.getTenantId(),getCurrentUser().getDeptId()));
            this.hazardReportService.createHazardReport(hazardReport);
            return new FebsResponse().success();
        } catch (Exception e) {
            String message = "新增隐患上报失败";
            log.error(message, e);
            return failure(e,message);
        }
    }

    /**
     * 逻辑删除 隐患上报
     * @author wanghw
     * @date 2024-08-20 09:23:04
     */
    @Log("逻辑删除HazardReport")
    @GetMapping("hazardReport/delete/{id}")
    @ResponseBody
    @RequiresPermissions(value={"hazardReport:delete","hazard:manager"},logical= Logical.OR)
    public FebsResponse deleteHazardReport(@PathVariable("id") String hazardReportIds) throws FebsException {
        try {
            HazardReport hazardReport = new HazardReport();
            hazardReport.setDeletedBy(getCurrentUser().getUserName());
            hazardReport.setDeletedTime(new Date());
            hazardReport.setDeletedFlg(FebsConstant.INVALID);
            this.hazardReportService.deleteHazardReport(hazardReport,hazardReportIds);
            return new FebsResponse().success();
        } catch (Exception e) {
            String message = "删除隐患上报失败";
            log.error(message, e);
            return failure(e,message);
        }
    }

//    /**
//     * 提交 隐患上报
//     * @author wanghw
//     * @date 2024-08-20 09:23:04
//     */
//    @Log("逻辑删除HazardReport")
//    @GetMapping("hazardReport/submit/{id}")
//    @ResponseBody
//    @RequiresPermissions("hazardReport:edit")
//    public FebsResponse submitHazardReport(@PathVariable("id") String hazardReportId) throws FebsException {
//
//        try {
//            HazardReport report = hazardReportService.findHazardReportById(hazardReportId);
//            if(ObjectUtils.isEmpty(report)){
//                return new FebsResponse().fail().message("待整改的隐患信息不存在!");
//            }
//            if (!ObjectUtils.isEmpty(report) &&
//                    !HazardConstant.HAZARD_STATUS.UPLOAD.equals(report.getStatus())
//                    && !HazardConstant.HAZARD_STATUS.BACK_PLAN.equals(report.getStatus())){
//                return new FebsResponse().fail().message("待整改的隐患信息已提交！");
//            }
//            HazardReport hazardReport = new HazardReport();
//            hazardReport.setUpdatedBy(getCurrentUser().getUserName());
//            hazardReport.setUpdatedTime(new Date());
//            hazardReport.setStatus(HazardConstant.HAZARD_STATUS.PLAN);
//            this.hazardReportService.submitHazardReport(hazardReport,hazardReportId);
//            return new FebsResponse().success();
//        } catch (Exception e) {
//            String message = "提交隐患上报失败";
//            log.error(message, e);
//            throw new FebsException(message);
//        }
//    }



    /**
     * 修改 隐患上报
     * @author wanghw
     * @date 2024-08-20 09:23:04
     */
    @Log("修改隐患上报")
    @PostMapping("hazardReport/update")
    @ResponseBody
    @RequiresPermissions("hazardReport:edit")
    public FebsResponse updateHazardReport(@RequestBody HazardReportDto hazardReport) throws FebsException {
        checkParams(hazardReport);
        if(StringUtils.isBlank(hazardReport.getReportId())){
            throw new FebsException("隐患类型ID不能为空");
        }
        if(!HazardConstant.HAZARD_STATUS.UPLOAD.equals(hazardReport.getStatus()) &&
                !HazardConstant.HAZARD_STATUS.PLAN.equals(hazardReport.getStatus())){
            throw new FebsException("非法的隐患状态");
        }
        try {
            hazardReport.setUpdatedBy(getCurrentUser().getUserName());
            this.hazardReportService.updateHazardReport(hazardReport);
            return new FebsResponse().success();
        } catch (Exception e) {
            String message = "修改隐患上报失败";
            log.error(message, e);
            return failure(e,message);
        }
    }

    /**
     * 导出 隐患上报的excel
     * @author wanghw
     * @date 2024-08-20 09:23:04
     */
    @PostMapping("hazardReport/excel")
    @ResponseBody
    @RequiresPermissions("hazardReport:view")
    public void export(QueryRequest queryRequest, HazardReportDto hazardReport, HttpServletResponse response) throws FebsException {
        try {
            List<HazardReportDto> hazardReports = this.hazardReportService.findHazardReportPage(queryRequest, hazardReport).getRecords();
            ExcelKit.$Export(HazardReport.class, response).downXlsx(hazardReports, false);
        } catch (Exception e) {
            String message = "导出Excel失败";
            log.error(message, e);
            throw new FebsException(message);
        }
    }

    private void checkParams(HazardReportDto hazardReport) throws FebsException {
        if(CollectionUtils.isEmpty(hazardReport.getFileList())){
            throw new FebsException("隐患类型图片不能为空");
        }
        if(StringUtils.isBlank(hazardReport.getTenantId())){
            throw new FebsException("公司Id不能为空");
        }
        if(StringUtils.isBlank(hazardReport.getHazardPlace())){
            throw new FebsException("隐患位置能为空");
        }
        if(StringUtils.isBlank(hazardReport.getHazardDescription())){
            throw new FebsException("隐患描述不能为空");
        }
        if(StringUtils.isBlank(hazardReport.getStatus())){
            throw new FebsException("隐患状态不能为空");
        }


    }

}
